package training_camp.day2.leetcode54;

import java.util.ArrayList;
import java.util.List;

class Solution {
     private final int[][] DIR = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

     public  List<Integer> spiralOrder(int[][] matrix) {
        int n = matrix.length;
        int m = matrix[0].length;
        List<Integer> list = new ArrayList<>();
        int x = 0;
        int y = 0;
        int di = 0;
        for (int i = 0; i < m * n; i++) {
            list.add(matrix[x][y]);
            matrix[x][y] = Integer.MAX_VALUE;
            int dx = x + DIR[di][0];
            int dy = y + DIR[di][1];
            if (dx >= n || dx < 0 || dy >= m || dy < 0 || matrix[dx][dy] == Integer.MAX_VALUE) {
                di = (di + 1) % 4;
            }
            x = x + DIR[di][0];
            y = y + DIR[di][1];
        }
        return list;
    }
}